package com.geely.club.util.openapiclient;

import com.geely.club.util.common.ServerConfig;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import cn.evun.gap.openapi.client.binding.RopClientException;
import cn.evun.gap.openapi.client.binding.ServiceRegistry;

/**
 * Created by mengyangyang on 2015-10-15.
 */
public final class OpenApiContext {

    private static final String OPEN_API_CONFIG_PROPERTIES = "/conf/openapi-client.properties";

    private static final String OPEN_API_APP_KEY = "gap.openapi.client.appkey";

    private static final String OPEN_API_APP_SECRET = "gap.openapi.client.secretkey";

    private static final String OPEN_API_SERVICE_URL = "gap.openapi.client.serviceurl";

    private static final Logger logger = Logger.getLogger(OpenApiContext.class.getSimpleName());

    private static ServiceRegistry serviceRegistry;

    private static final Map<Class<?>, Object> beanMap = new HashMap<Class<?>, Object>();

    private OpenApiContext() {
    }

    private static void initialize() {
        if (null == serviceRegistry) {
            serviceRegistry = new ServiceRegistry();
            OpenApiClient openApiClient = new OpenApiClient();

            openApiClient.setAppkey(ServerConfig.APP_KEY);
            openApiClient.setServiceUrl(ServerConfig.SERVER_URL);
            openApiClient.setSecret(ServerConfig.SECRET_KEY);
            serviceRegistry.setOpenApiClient(openApiClient);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> type) {

        initialize();

        T object = (T) beanMap.get(type);

        if (null == object) {
            object = serviceRegistry.getService(type);
            if (null == object) {
                throw new RopClientException("can't find bean named " + type.getSimpleName() + ", please check out!");
            }
            beanMap.put(type, object);
        }

        return object;
    }
}
